package com.njmaomao.gj.pyot.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Predicates.and;

@Configuration
@EnableSwagger2
//@Profile({"dev", "test"})
public class SwaggerConfig {


    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${server.port}")
    private String port;
    private static final String splitor = ";";

    @Bean
    public Docket createMaApi() {
        System.out.println("http://127.0.0.1:" + port + contextPath + "/swagger-ui.html");
        List<Parameter> pars = addHeader();
        return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false)
                .groupName("支付-圆通对接接口")
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(and(basePackage("com.njmaomao.gj.pyot.controller"),
                        RequestHandlerSelectors.withClassAnnotation(RestController.class)))
                .paths(PathSelectors.any())
                .build()/*.globalOperationParameters(pars)*/;
    }

    protected List<Parameter> addHeader() {
        List<Parameter> pars = new ArrayList<Parameter>();
        ParameterBuilder ticketPar = new ParameterBuilder();
        ticketPar.name("token").description("用户token")
                .modelRef(new ModelRef("string")).parameterType("header")
                //header中的token参数非必填，传空也可以
                .required(false);
        ParameterBuilder devIdPar = new ParameterBuilder();
        devIdPar.name("openId").description("openId")
                .modelRef(new ModelRef("string")).parameterType("header")
                //header中的token参数非必填，传空也可以
                .required(false);
        //根据每个方法名也知道当前方法在设置什么参数
        pars.add(ticketPar.build());
        pars.add(devIdPar.build());
        return pars;
    }

    //构建 api文档的详细信息函数
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .version("1.0.0")
                .description("application:[gj001]")
                .build();
    }


    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
